package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.ArticleInfoDto;
import com.heima.model.user.dtos.UserRelationDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApuUerFollow;
import com.heima.user.mapper.ApuUerFollowMapper;
import com.heima.user.service.ApUserService;
import com.heima.user.service.ApuUerFollowService;
import com.heima.utils.thread.AppThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class ApuUerFollowServiceimpl extends ServiceImpl<ApuUerFollowMapper,ApuUerFollow> implements ApuUerFollowService {
    @Autowired
    private ApUserService apUserService;
    /**
     * 查询关注数据
     * @param dto
     * @return
     */
    @Override
    public ApuUerFollow gz(ArticleInfoDto dto,Long id) {
        ApuUerFollow apuUerFollow = getOne(Wrappers.<ApuUerFollow>lambdaQuery().eq(ApuUerFollow::getUserId, id).eq(ApuUerFollow::getFollowId, dto.getAuthorId()));
        return apuUerFollow;
    }

    /**
     * 关注
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public ResponseResult follow(UserRelationDto dto) {
        Integer id = AppThreadLocalUtil.getUser().getId();
        if(dto.getAuthorId()!=null||dto.getOperation()!=null){
        LambdaQueryWrapper<ApuUerFollow> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(ApuUerFollow::getUserId, id);
        wrapper.eq(ApuUerFollow::getFollowId,dto.getAuthorId());
        ApuUerFollow apuUerFollow = getOne(wrapper);
        if (apuUerFollow==null&&dto.getOperation()==0){
            ApuUerFollow apuUerFollow1 = new ApuUerFollow();
            apuUerFollow1.setUserId(id);
            apuUerFollow1.setFollowId(dto.getAuthorId());
            ApUser apUser = apUserService.getById(id);
            apuUerFollow1.setFollowName(apUser.getName());
            apuUerFollow1.setLevel((short)1);
            apuUerFollow1.setIsNotice((short)0);
            apuUerFollow1.setCreatedTime(new Date());
            //保存
            save(apuUerFollow1);
            return ResponseResult.okResult("已关注");
        }else {
            removeById(apuUerFollow.getId());
            return ResponseResult.okResult("取消关注");
        }
    }
        return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
    }
}
